<template>
  <view style="padding: 10px">
    <uni-file-picker  ref="files"  @select="afterRead"/>
<!--    <van-uploader v-model="photoList" :max-count="1" :after-read="afterRead"></van-uploader>-->
    <!--    <van-button type="primary">主要按钮</van-button>-->
    <image v-for="(item,index) in photoList" :src="item.contentNew" style="width: 100%" mode="widthFix"></image>
  </view>
</template>

<script>
import Compressor from "compressorjs"

export default {
  name: "photo",
  data() {
    return {
      photoList: [],
    }
  },
  mounted() {
  },
  methods: {
    fileToBase64(file) {
      return new Promise(resolve => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          return resolve(e.target.result)
        };
      })
    },
    afterRead(file) {
      let mfile = file.tempFiles[0].file
      console.log(mfile)
      new Compressor(mfile, {
        quality: 0.2,
        // The compression process is asynchronous,
        // which means you have to access the `result` in the `success` hook function.
        success: async result => {
          const formData = new FormData();
          // The third parameter is required for server
          formData.append('file', result, result.name);
          console.log(result)
          let base64File = await this.fileToBase64(result)
          this.photoList.push({contentNew:base64File})
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    async imgPreview(file) {
      console.log(file.file)
      console.log(file.file.name, file.file.type)
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return
      if (/^image/.test(file.file.type)) {
        let result = await this.imgCompress(file.file)
        console.log("imgPreview", result)
      }
    },
    async imgCompress(file) {
      // 将文件转img对象
      const imgObj = await this.fileToImg(file)
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas')
        const context = canvas.getContext('2d')
        // 获取文件宽高比例
        const {width: originWidth, height: originHeight} = imgObj
        // 自定义等比例缩放宽高属性，这里我用的是固定800宽度，高度是等比例缩放
        const scale = +(originWidth / originHeight).toFixed(2) // 比例取小数点后两位)
        const targetWidth = 800 // 固定宽
        const targetHeight = Math.round(800 / scale) // 等比例缩放高

        canvas.width = targetWidth
        canvas.height = targetHeight
        context.clearRect(0, 0, targetWidth, targetHeight)
        // canvas重新绘制图片
        context.drawImage(imgObj, 0, 0, targetWidth, targetHeight)
        // canvas转二进制对象转文件对象，返回
        const type = 'image/png'
        canvas.toBlob(function (blob) {
          const f = new File([blob], file.name, {
            type,
            lastModified: file.lastModified
          })
          resolve(f)
        }, type)
      })
    },
    async fileToImg(file) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        const reader = new FileReader()
        reader.onload = function (e) {
          img.src = e.target.result
        }
        reader.onerror = function (e) {
          reject(e)
        }
        reader.readAsDataURL(file)
        img.onload = function () {
          resolve(img)
        }
        img.onerror = function (e) {
          reject(e)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
